package com.lagou.service;

import com.lagou.handler.RpcServerHandler;
import com.lagou.runnable.ResponseThread;
import com.lagou.service.com.lagou.zookeeper.ServiceRegistry;
import com.lagou.service.com.lagou.zookeeper.ZooKeeperServiceRegistry;

import org.springframework.stereotype.Service;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

@Service
public class UserServiceImpl implements UserService {

    private static ServiceRegistry serviceRegistry = new ZooKeeperServiceRegistry("127.0.0.1");

    public String sayHello(String word) {
        System.out.println("调用成功--参数 "+word);
        return "调用成功--参数 "+word;
    }

    //hostName:ip地址  port:端口号
    public static void startServer(String serviceAddress) throws InterruptedException {

        ResponseThread responseThread = new ResponseThread();
        responseThread.start();

        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new RpcDecoder(RpcRequest.class,new JSONSerializer()));
                        pipeline.addLast(new RpcServerHandler());

                    }
                });

        serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024);
        serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
        // 获取 RPC 服务器的 IP 地址与端口号
        String[] addressArray = serviceAddress.split(":");
        String ip = addressArray[0];
        int port = Integer.parseInt(addressArray[1]);
        // 启动 RPC 服务器
        ChannelFuture future = serverBootstrap.bind(ip, port).sync();
        // 注册 RPC 服务地址
        if (serviceRegistry != null) {
            serviceRegistry.register(UserService.class.getName(), serviceAddress);
            System.out.println("register service: "+UserService.class.getName()+"===="+serviceAddress);
        }
        System.out.println("server started on port " + port);
        // 关闭 RPC 服务器
        future.channel().closeFuture().sync();

//        serverBootstrap.bind(hostName,port).sync();
        System.out.println("服务启动！");


    }

}
